package com.ttbj.controller.sysuser;

import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ttbj.product.api.DriverFacade;
import com.ttbj.product.bean.dto.DriverDto;
import com.ttbj.product.bean.dto.TruckDto;
import com.ttbj.product.bean.dto.ViewData;
import com.ttbj.util.ResultUtil;
import com.ttbj.util.ViewModelUtil;
import cn.jiguang.common.utils.StringUtils;

/**
 * 公司司机接口
 * .根据用户车牌参数模糊查询车辆信息 
 * .捆绑车辆信息
 * @author Medivh
 */

@Controller
@RequestMapping("/driver")
public class OrgDriverController {

	
	@Autowired
	private DriverFacade driverFacade = null;
	
	/**
	 * 模糊查询车辆信息 
	 * @param carNum
	 * 			模糊查询参数
	 * @param token
	 * 			token			
	 * @throws Exception 
	 */
	@RequestMapping(value = "/query/truck.do", method = RequestMethod.POST)
	@ResponseBody
	public ViewData likeTruck(HttpServletRequest request,String carNum, String token) throws Exception {
		if(StringUtils.isEmpty(carNum) || carNum.contains("%")){
			return ResultUtil.createFail("messages", 911, "车牌号" );
		}
	    List<TruckDto> list = driverFacade.likeTruck(carNum);
		return ViewModelUtil.buildSuccessPage("成功", list, list.size());
	}

	/**
	 * 选择捆绑车辆车辆信息
	 * @param driver
	 *            司机信息
	 * @param token
	 */
	@RequestMapping(value = "/option/truck.do", method = RequestMethod.POST)
	@ResponseBody
	public ViewData optionTruck(HttpServletRequest request, Long truckId, String token) throws Exception {
		DriverDto driverDto = (DriverDto) request.getAttribute("user");
		if(null == truckId){
			return ResultUtil.createFail("messages", 911,"车牌号" );
		}
		DriverDto  truckIncludeDriverDto = new DriverDto().truckId(truckId);
		DriverDto existDto = driverFacade.findDriver(truckIncludeDriverDto, 1);
		if(null == existDto || existDto.getDriverToken().equals(token)){//查看车牌号有没有关联重复
				driverFacade.updateTruck(new TruckDto(truckId,driverDto.getDriverId())); //关联司机
			 return   driverFacade.cmplData(truckIncludeDriverDto.id(driverDto.getDriverId()));//关联车辆
		}
		return  ViewModelUtil.buildFailure(15, "车辆已占用",existDto) ;
	}
	
	/**
	 * 解除车辆绑定
	 */
	@RequestMapping(value = "/relieve/truck.do", method = RequestMethod.POST)
	@ResponseBody
	public ViewData relieveTruck(HttpServletRequest request,  String token) throws Exception {
		DriverDto driverDto = (DriverDto) request.getAttribute("user");
		driverFacade.updateTruck(new TruckDto(driverDto.getDriverTruck(), -1l));
		driverDto.truckId(-1l);
		return driverFacade.cmplData(driverDto);
	}

}
